const express = require('express');
const mysqla = require('mysql');
const app = express();
app.use(express.static('www'));
const mysql = mysqla.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'xiaomi'
})
mysql.connect(function (err) {
    if (err) {
        console.log('连接数据库失败了');
    }
})

app.get('/homelist', function (req, res) {
    var sql = `select * from xiao_mi`;
    mysql.query(sql, function (err, data) {
        if (err) {
            res.json({ success: 0, data: '执行sql语句失败xiaomi' })
        } else {
            res.json({ success: 1, data })
        }
    })
})


app.get('/homeshop', function (req, res) {
    console.log(req); // 商品id
    var sql = `select * from shop where xiao_id=${req.id}`;
    
    mysql.query(sql, function (err, data) {
        console.log(sql);
        if (err) {
            res.json({ success: 0, data:req })
            return;
        }
        console.log(data); // [] 空数组

        // 获取的data中 如果没有值 [0]等于undefined为false
        // 如果有值 [0]等于获取的信息对象 为true
        if (data[0]) {
            console.log('当前商品在数据库已存在')
            return;
        }

        console.log('当前商品数据库没有');
        var sql2 = `select * from xiao_mi where id=${req}`;
        mysql.query(sql2, function (err, data) {
            if (err) {
                res.json({ success: 0, data: '执行sql语句失败xiaomi2222' });
                return;
            }
            // 获取的当前点击的商品的所有信息
            console.log(data);
            var sql3 = `insert into shop(title,url,desc_1,price,xiao_id) values ("${data[0].title}","${data[0].url}","${data[0].desc_1}","${data[0].price}","${data[0].id}"`;
            console.log(sql3);
            mysql.query(sql3, function (err) {
                if (err) {
                    res.json({ success: 0, data: '执行sql语句失败1' })
                    return;
                }
                res.json({ success: 1, data: '加入购物车成功' });
            })
        })
    })



})


app.listen(3000, function () {
    console.log('http://localhost:3000');
})